from django.shortcuts import render

# Create your views here.
from rest_framework import request
from rest_framework import status
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from users.models import User, Address

# 用户名验证
from users.serializers import RegisterUserSerializer, PeopleTokenSerializer, EmailAPIVIewSerializer, \
    UserAdressAPIViewSerializer, UserHestoryAPIViewSerializer, SKUSerializer
from users.utils import generic_verify_url, check_verify_url


class RegisterUsernameCountAPIView(APIView):

    def get(self,request,username):

        count = User.objects.filter(username=username).count()

        data= {
            'count':count,
            'username':username
        }
        return Response(data)


# 手机号的验证
class RegisterMobileAPIView(APIView):
    # get 请求   GET /users/phones/(?P<mobile>1[345789]\d{9})/count/
    def get(self,request,mobile):
        # 取得是否在数据库中有手机号的存在
        count = User.objects.filter(models=mobile).count()

        data ={
            'count':count
        }

        return Response(data)


# # 注册的验证　
# class RegisterUserAPIView(APIView):
#
#    def post(self,request):
#
#        data = request.data
#
#        serializer = RegisterUserSerializer(data=data)
#        serializer.is_valid(raise_exception=True)
#
#        serializer.save()
#
#        return Response(serializer.data)
#
# '''
# 1 前端传进来数据　
# 2 后端接收　
# 3 序列化器的校验
# 4 序列化器的保存
#
# '''
# 三级视图的使用　
from rest_framework.generics import CreateAPIView, GenericAPIView


class RegisterUserAPIView(CreateAPIView):
    serializer_class = RegisterUserSerializer



'''
逻辑　前端　　token  id

jwt 认证　　可以选择token

序列化器　选择　　M  解析token 得到user 对象

返回结果

'''


# from rest_framework.permissions import IsAuthenticated
# class PeopleToken(APIView):
#
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#         user = request.user
#         serializer = PeopleTokenSerializer(user)
#         serializer.is_valid(raise_exception=True)
#
#         return Response(serializer.data)


'''
三级视图使用　
'''
from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated


class PeopleToken(RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PeopleTokenSerializer

    def get_object(self):

        return self.request.user


'''
参数　邮箱　token
请求方式　put
进行更新　
序列化器的选择　Ｍ

'''


class EmailAPIVIew(APIView):
    permission_classes = [IsAuthenticated]

    def put(self,request):

        data = request.data

        user = request.user

        serializer = EmailAPIVIewSerializer(instance=user,data=data)
        serializer.is_valid(raise_exception=True)

        serializer.save()
        from django.core.mail import send_mail
        # subject, message, from_email, recipient_list,
        # subject,       主题
        subject = '美多商场激活邮件'
        #  message,     信息
        message = ''
        # from_email,   发件人
        from_email = '美多商城<qi_rui_hua@163.com>'
        # recipient_list,   收件人列表
        email = request.data.get('email')
        recipient_list = [email]

        verify_url = generic_verify_url(request.user.id, email)

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)

        from celery_tasks.email.tasks import send_verify_mail

        send_verify_mail.delay(email,verify_url)

        return Response(serializer.data)


'''
GET /users/emails/verification/
请求方式　get　参数　token
返回的参数　成功message

'''


class EmailsVerificationAPIView(APIView):

    def get(self,request):
        # 接受参数　
        token = request.query_params.get('token')
        # 校验参数
        user = check_verify_url(token)
        # 判断user
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()

        return Response({'message':'OK'})


'''
增加地址
接收前端传过来的参数　　用户id 收货人　地址　　详细地址　手机号　固定电话　邮箱　可选填写
校验　手机号校验　用户的id token 　　
保存到数据库中　　create 　还需要创建一个模型表
返回成功

'''
'''
 "PUT /users/addresses/6/status/
 设置默认地址　请求类型　put
 将编号为


'''


class UserAdressAPIView(ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
    permission_classes = [IsAuthenticated]
    # serializer_class = UserAdressAPIViewSerializer
    # queryset = Address.objects.all()

    def get(self,request):
        user = request.user
        try:
            address = Address.objects.filter(user = user).all()
        except Address.DoesNotExist:
            return Response({'msm':'没有地址'})
        serializer = UserAdressAPIViewSerializer(instance=address,many=True)
        # serializer.is_valid(raise_exception=True)

        return Response(serializer.data)
        # return self.list(request)

    def post(self,request):

        data = request.data

        user = request.user

        serializer = UserAdressAPIViewSerializer(data=data,context={'user':user})
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)
        # return self.create(request)

    # def put(self, request,id):
    #     data = request.data
    #     user = request.user
    #     serializer = SKUSerializer(isinstance=user, data=data,context={'id':id})
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response({'msm': 'OK'}, status=status.HTTP_200_OK)


'''
历史访问　
１　需要商品id  用户id
２　进行验证
３　保存
４　返回响应

'''
from django_redis import get_redis_connection


class UserHistoryAPIView(CreateAPIView):

    permission_classes = [IsAuthenticated]

    serializer_class = UserHestoryAPIViewSerializer

    def get(self,request):

        user = request.user

        redis_conn = get_redis_connection('history')

        redis_sku_id = redis_conn.lrange('history_%s'%user.id,0,4)

        sku = []

        for sku_id in redis_sku_id:
            sku_obj = SKU.objects.filter(pk=sku_id)
            sku.append(sku_obj)

        serializer = SKUSerializer(data=sku,many=True)
        serializer.is_valid(raise_exception=True)

        return Response(serializer.data)


class UserAUthorizationAPIView(ObtainJSONWebToken):

    def post(self,request):

        response = super().post(request)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 获取用户
            user = serializer.validated_data.get('user')
            response = merge_cart_cookie_to_redis(request, user, response)

            return response

        return response
